package com.dhcc.core.modules.common.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.dhcc.core.config.properties.SysProperties;
import com.dhcc.core.framework.annotion.Permission;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.constant.Const;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.util.ArrayUtil;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.ZipUtil;
import com.dhcc.core.modules.common.entity.FileEntity;
import com.dhcc.core.modules.msgcenter.MsgPushUtil;
import com.google.common.collect.Lists;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;

/**
 * 资源控制器
 * 
 * @ClassName: ResourceManagerController
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午10:18:51
 */
@Controller
@RequestMapping("/resmanager")
public class ResourceManagerController extends BaseController {

    @Autowired
    private SysProperties sysProperties;

    /**
     * 管理页
     */
    @Permission(roles = Const.ADMIN_NAME)
    @RequestMapping
    public String index(@RequestParam(value = "path", required = false) String path,
            @RequestParam(value = "target", required = false) String target,
            @RequestParam(value = "thumb", required = false) String thumb,
            @RequestParam(value = "filterName", required = false) String filterName, Model model) {
        String absolutePath = sysProperties.getSysHome();
        String parentPath = "";
        if (CommonUtil.isEmpty(path)) {
            path = parentPath;
        } else {
            String[] _array = ArrayUtil.stringToArray(path, "/");
            for (int i = 0; i < (_array.length - 1); i++) {
                if (i == 0) {
                    parentPath = _array[i];
                } else {
                    parentPath += "/" + _array[i];
                }
            }
        }

        absolutePath = absolutePath + path;
        List<FileEntity> result = Lists.newArrayList();
        File mainFile = new File(absolutePath);
        if (!mainFile.exists()) {
            mainFile.mkdirs();
        }
        for (File file : mainFile.listFiles()) {
            if (CommonUtil.isEmpty(filterName) || file.getName().indexOf(filterName) > -1) {
                if (file.isDirectory()) {
                    FileEntity templateFile = new FileEntity();
                    templateFile.setFileName(file.getName());
                    templateFile.setFilePath(path + "/" + file.getName());
                    templateFile.setFileLastTime(DateUtil.formatDateTime(new Date(file.lastModified())));
                    templateFile.setFileType("文件夹");
                    templateFile.setIsDirectory(file.isDirectory());
                    result.add(templateFile);
                }

            }
        }
        for (File file : mainFile.listFiles()) {
            if (CommonUtil.isEmpty(filterName) || file.getName().indexOf(filterName) > -1) {
                if (!file.isDirectory()) {
                    FileEntity templateFile = new FileEntity();
                    templateFile.setFileName(file.getName());
                    templateFile.setFilePath(path + "/" + file.getName());
                    templateFile.setFileLastTime(DateUtil.formatDateTime(new Date(file.lastModified())));
                    templateFile.setFileType(FileUtil.getType(file));
                    templateFile.setFileSize(file.length());
                    templateFile.setIsDirectory(file.isDirectory());
                    result.add(templateFile);
                }

            }
        }
        model.addAttribute("fileList", result);
        model.addAttribute("currentPath", path);
        model.addAttribute("parentPath", parentPath);
        model.addAttribute("target", target);
        model.addAttribute("thumb", thumb);
        model.addAttribute("filterName", filterName);
        MsgPushUtil.me().pushUser("message", "kwgkwg",  "kwgkwg", null,this.getLoginUser(), "1044767080057335810","a");
        return "/resmanager.html";
    }

    /**
     * 上传文件
     */
    @Permission(roles = Const.ADMIN_NAME)
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public R handleFileUpload(@RequestParam(value = "path", required = true) String path, HttpServletRequest request) {
        String fileSavePath = sysProperties.getSysHome();
        if (CommonUtil.isEmpty(path)) {
            path = "";
        }
        fileSavePath = fileSavePath + path;

        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file[]");
        File dir = new File(fileSavePath);
        if (!dir.exists()) {
            throw new BizException("请确认上传的目录!");
        }
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            try {
                file.transferTo(new File(fileSavePath + File.separator + fileName));
            } catch (Exception e) {
                throw new BizException(BizExceptionEnum.UPLOAD_ERROR);
            }
        }
        return R.ok();
    }

    /**
     * 新建文件夹
     */
    @Permission(roles = Const.ADMIN_NAME)
    @RequestMapping(method = RequestMethod.POST, path = "/folder")
    @ResponseBody
    public R folder(@RequestParam(value = "path", required = true) String path,
            @RequestParam(value = "folder", required = true) String folder) {
        String fileSavePath = sysProperties.getSysHome();
        if (CommonUtil.isEmpty(path)) {
            path = "";
        }
        fileSavePath = fileSavePath + path;

        File dir = new File(fileSavePath + File.separator + folder);
        if (!dir.exists()) {
            dir.mkdirs();
        } else {
            throw new BizException("文件夹已存在！");
        }
        return R.ok();
    }

    /**
     * 删除文件
     */
    @Permission(roles = Const.ADMIN_NAME)
    @RequestMapping(method = RequestMethod.POST, path = "/delete")
    @ResponseBody
    public R delete(@RequestParam(value = "path", required = true) String[] path) {
        String absolutePath = sysProperties.getSysHome();
        if (CommonUtil.isEmpty(path)) {
            throw new BizException("未选择文件！");
        }
        for (String _path : path) {
            File _file = new File(absolutePath + _path);
            if (!_file.exists()) {
                throw new BizException("文件不存在！");
            } else {
                FileUtil.del(_file);
            }
        }
        return R.ok();
    }

    /**
     * 下载文件
     * 
     * @throws IOException
     */
    @Permission(roles = Const.ADMIN_NAME)
    @RequestMapping(method = RequestMethod.POST, path = "/download")
    @ResponseBody
    public void download(@RequestParam(value = "path", required = true) String[] path, HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        String absolutePath = sysProperties.getSysHome();
        if (CommonUtil.isEmpty(path)) {
            throw new BizException("未选择文件！");
        }
        byte[] bytes = null;
        if (path.length > 1) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ZipOutputStream zipOut = new ZipOutputStream(outputStream);
            for (String _path : path) {
                File _file = new File(absolutePath + _path);
                if (!_file.exists()) {
                    throw new BizException("文件不存在！");
                } else {
                    ZipUtil.toZip(_file, zipOut);
                }
            }
            IoUtil.close(zipOut);
            bytes = outputStream.toByteArray();
        } else {
            File _file = new File(absolutePath + path[0]);
            if (!_file.exists()) {
                throw new BizException("文件不存在！");
            } else {
                if (_file.isDirectory()) {
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    ZipUtil.toZip(_file, outputStream);
                    bytes = outputStream.toByteArray();
                } else {
                    bytes = FileUtil.readBytes(_file);
                }
            }
        }
        try {
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            throw new BizException("文件不存在！");
        }
    }
}
